package com.auth.config;

import cn.hutool.Hutool;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aaa.util.Result;
import com.aaa.util.TokenObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * security的配置文件
 */

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //
        http.formLogin().loginProcessingUrl("/userlogin")
                .successHandler(getSucceehandler())// 前后端分离
                .failureHandler(getFailHandler())
                .and()
                .authorizeRequests().antMatchers("/userlogin","/","/oauth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
        http.cors();
    }

    /**
     * 认证失败的handler
     * @return
     */
    @Bean
    public AuthenticationFailureHandler getFailHandler() {
        return (httpServletRequest, httpServletResponse, e) -> {
            Result fail = Result.fail("失败");
            printJsonData(httpServletResponse,fail);
        };
    }

    /**
     * 认证成功之后走的handler
     * @return
     */

    @Bean
    public AuthenticationSuccessHandler getSucceehandler() {
        //  返回token的值
        // localhost:8500/oauth/token?grant_type=password&client_id=admin&client_secret=123456&username=yyl&password=123456
        // 代码发出post请求
        return (httpServletRequest, httpServletResponse, authentication) -> {
            // http请求
            HttpRequest post = HttpUtil.createPost("http://localhost:8085/oauth/token");
            post.form("grant_type","password");
            post.form("client_id","admin");// 第三方客户端的用户名
            post.form("client_secret","123456");//第三方客户端的密码
            // &username=yyl&password=123456
            String username = httpServletRequest.getParameter("username");
            String password = httpServletRequest.getParameter("password");
            post.form("username",username);// 输入的用户名
            post.form("password",password);// 输入夫人密码

            HttpResponse response = post.execute();// 执行

            System.out.println(response);
            String body = response.body();// 获取包体
            //  hutool工具  将  json 字符串转换为接送对象
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String access_token = (String) jsonObject.get("access_token");
            String token_type = (String) jsonObject.get("token_type");
            String token =token_type+access_token;
            //  给  前端 响应
            Result success = Result.success(token);
            printJsonData(httpServletResponse,success);
        };

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

//        auth.userDetailsService().passwordEncoder()
        auth.inMemoryAuthentication()
                .passwordEncoder(getPasswordEncoder())
                .withUser("yyl")
                .password(getPasswordEncoder().encode("123456"))
                .roles("ADMIN");
    }


    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 密码模式的时候需要的一个对象
     * @return
     * @throws Exception
     */

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    public void printJsonData(HttpServletResponse httpServletResponse,Result success) throws IOException {
        //

        ObjectMapper objectMapper = new ObjectMapper();
        httpServletResponse.setContentType("application/json;charset=utf8");
        PrintWriter writer = httpServletResponse.getWriter();
        String s = objectMapper.writeValueAsString(success);
        writer.print(s);
        writer.flush();
        writer.close();
    }
}
